package com.cloudcc.mobile.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.util.ImageUtils;
import com.cloudcc.mobile.util.UrlTools;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class ChosePersonAdapter extends BaseAdapter implements SectionIndexer {
    protected final int[] colors;
    private List<CoworkerEntity> list = null;
    private Context mContext;

    public ChosePersonAdapter(Context mContext, List<CoworkerEntity> list) {
        this.mContext = mContext;
        this.list = list;
        String[] array = mContext.getResources().getStringArray(
                R.array.logo_colors);
        colors = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            colors[i] = Color.parseColor(array[i]);
        }
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<CoworkerEntity> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public int getCount() {
        return this.list.size();
    }

    public CoworkerEntity getItem(int position) {
        return list.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @SuppressWarnings("unused")
    public View getView(final int position, View view, ViewGroup arg2) {
        ViewHolder viewHolder = null;
        final CoworkerEntity mContent = list.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(
                    R.layout.chose_item, null);
            viewHolder.tvTitle = (TextView) view.findViewById(R.id.title);
//            viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        // 根据position获取分类的首字母的Char ascii值
        int section = getSectionForPosition(position);
        // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
//        if (position == getPositionForSection(section)) {
////            viewHolder.tvLetter.setVisibility(View.VISIBLE);
//            viewHolder.tvLetter.setText(mContent.getSortLetters());
//        } else {
////            viewHolder.tvLetter.setVisibility(View.GONE);
//        }

        // String uri=UrlTools.getTopImage(mContent.getId());
        // String icon=mContent.getId()+".png";
        // String iconpath=Tools.getImagePath("/CloudCC/UserIcon/")+"/"+icon;
        // File file=new File(iconpath);
		/*
		 * if(file.exists()){ // Constants.imageLoader.displayImage("file://" +
		 * iconpath, viewHolder.icon, Constants.Contact_options);
		 * viewHolder.icon.setImageBitmap(ImageUtils.loadBitmap(iconpath));
		 * }else{ // ImageLoader.getInstance().displayImage(uri,
		 * viewHolder.icon, Constants.Contact_options); ImageLoadingListener
		 * animateFirstListener = new AnimateFirstDisplayListener(icon);
		 * ImageLoader.getInstance().displayImage(uri, viewHolder.icon,
		 * Constants.Contact_options,animateFirstListener); }
		 */
        int colorindex = position % colors.length;
        String uri = UrlTools.getTopImage(this.list.get(position).getId());
        viewHolder.tvTitle.setText(this.list.get(position).getName());
        return view;
    }

    class ViewHolder {
        TextView tvLetter;
        TextView tvTitle;
        ImageView phone;
        ImageView message;
        ImageView guanzhu;
        ImageView icon;
        CheckBox box;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    public int getSectionForPosition(int position) {
        return list.get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = list.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 提取英文的首字母，非英文字母用#代替。
     *
     * @param str
     * @return
     */
    private String getAlpha(String str) {
        String sortStr = str.trim().substring(0, 1).toUpperCase();
        // 正则表达式，判断首字母是否是英文字母
        if (sortStr.matches("[A-Z]")) {
            return sortStr;
        } else {
            return "#";
        }
    }

    private static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {
        private String id;

        public AnimateFirstDisplayListener(String imageId) {
            this.id = imageId;
        }

        static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                    ImageUtils.saveImage("/CloudCC/UserIcon", id, loadedImage);// 图片保存
                }
            }
        }
    }

    @Override
    public Object[] getSections() {
        return null;
    }

}